﻿using System;
using System.Collections.Generic;
using System.Text;

using DupeKill.Core.IO;
using DupeKill.Core.Discovery;
using DupeKill.Core.Comparison; 

namespace DupeKill.Core
{
    public class FileSetComputation
    {
        private IFileIterator iterator; 
        private IFileSystemGateway fileSystem;
        private int chunkSize; 
        public FileSetComputation(IFileIterator iterator, IFileSystemGateway fileSystem, int chunkSize)
        {
            if (iterator == null)
                throw new ArgumentNullException();
            if (fileSystem == null)
                throw new ArgumentNullException();
            if (chunkSize < 1)
                throw new ArgumentException(); 

            this.iterator = iterator;
            this.fileSystem = fileSystem;
            this.chunkSize = chunkSize; 
        }

        public IEnumerable<FileSet> Compute()
        {
            FileSet input = new FileSet();
            new FileSetLoader(input).LoadAll(iterator); 

            FileSetComparerFactory factory = new FileSetComparerFactory(fileSystem);

            IFileSetComparer byLengthComparer = factory.CreateByLengthComparer();
            IFileSetComparer byContentComparer = factory.CreateByContentComparer(chunkSize); 

            foreach (FileSet equiSizeSet in byLengthComparer.CompareAndSplit(input))
            {
                if (equiSizeSet.Count > 1)
                {
                    foreach (FileSet equiContentSet in byContentComparer.CompareAndSplit(equiSizeSet))
                    {
                        yield return equiContentSet; 
                    }
                }
                else
                {
                    yield return equiSizeSet; 
                }
            }
        }
    }
}
